package com.GZX.Test;

import java.util.List;
import java.util.Random;

public class Student implements Runnable {
    private String studentId;
    private List<Course> courses;

    private volatile boolean hasEnrolled; // 添加一个变量来跟踪学生是否已经选课

    public Student(String studentId, List<Course> courses) {
        this.studentId = studentId;
        this.courses = courses;
        this.hasEnrolled = false; // 初始化为false，表示学生还未选课
    }
    public Random random = new Random();

    @Override
    public void run() {
        while (!hasEnrolled) { // 只要学生还没有选课，就继续尝试
            Course courseToEnroll = selectRandomCourse();
            if (courseToEnroll != null && courseToEnroll.enroll(studentId)) {
                hasEnrolled = true; // 选课成功后，设置hasEnrolled为true
                System.out.println(studentId + "----->选择课程:" + courseToEnroll.getcId());
            } else {
                // 选课失败，稍后重试
                try {
                    Thread.sleep((long) (Math.random() * 1000)); // 随机等待一段时间再尝试
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Course selectRandomCourse() {
        if (courses.isEmpty()) {
            return null; // 没有课程可选了
        }
        return courses.get(random.nextInt(courses.size())); // 随机选择一门课程
    }
}